package com.yungam.imcs.controller.person;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yungam.common.bean.role.Role;
import com.yungam.common.bean.team.Team;
import com.yungam.common.bean.user.User;
import com.yungam.common.response.RetDTO;
import com.yungam.common.service.RoleService;
import com.yungam.common.service.TeamService;
import com.yungam.common.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.*;

@Api(tags = "用户管理页面接口")
@RestController
@RequestMapping("/users")
public class UserController {

    @Resource
    private UserService userService;
    @Resource
    private TeamService teamService;
    @Resource
    private RoleService roleService;

    @ApiOperation("获取所有用户信息")
    @GetMapping("/user")
    public RetDTO<?> getUsers() {
        Map<String, Object> ans = new HashMap<>();
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.select(User.class, col -> !col.getProperty().equals("password")); // 过滤『密码』字段
        List<User> users = userService.list(qw); // 用户列表
        // 查询用户对应的班组名称, 角色名称
        Map<Integer, String> teamMapper = new HashMap<>(), roleMapper = new HashMap<>();
        List<Team> teams = teamService.list();
        for (Team team : teams) teamMapper.put(team.getId(), team.getTeamName());
        List<Role> roles = roleService.list();
        for (Role role : roles) roleMapper.put(role.getId(), role.getRoleName());
        // 整合数据
        for (User user : users) {
            if (user.getTeamId() != null && teamMapper.containsKey(user.getTeamId())) {
                user.setTeamName(teamMapper.get(user.getTeamId()));
            }
            if (user.getRoleId() != null && roleMapper.containsKey(user.getRoleId())) {
                user.setRoleName(roleMapper.get(user.getRoleId()));
            }
        }
        ans.put("user", users);
        ans.put("roleMapper", roleMapper); // 『select框』数据
        ans.put("teamMapper", teamMapper); // 『select框』数据
        return RetDTO.data(ans);
    }

    @ApiOperation("删除某一用户")
    @DeleteMapping("/user")
    public RetDTO<?> delOneUser(@ApiParam("用户 id") Integer id) {
        userService.removeById(id);
        return RetDTO.success();
    }

    @ApiOperation("添加用户")
    @PostMapping("/user")
    public RetDTO<?> addUser(@ApiParam("用户实体") @RequestBody User user) {
        //『用户账号』 查重
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("user_name", user.getUserName());
        User repeat = userService.getOne(qw);
        if (repeat != null) return RetDTO.error("该用户账号已经存在");
        // 密码加密
        if (StringUtils.isNotEmpty(user.getPassword())) {
            user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes(StandardCharsets.UTF_8)));
        }
        user.setCreateTime(new Date());
        user.setUserType(1); // 本系统新增的都是『IMCS』用户
        userService.save(user);
        return RetDTO.success();
    }

    @ApiOperation("更新用户")
    @PutMapping("/user")
    public RetDTO<?> updateUser(@ApiParam("用户实体") @RequestBody User user) {
        User old = userService.getById(user.getId());
        // 如果用户账号发生改变, 则需要查重
        if (!Objects.equals(user.getUserName(), old.getUserName())) {
            QueryWrapper<User> qw = new QueryWrapper<>();
            qw.eq("user_name", user.getUserName());
            User repeat = userService.getOne(qw);
            if (repeat != null) return RetDTO.error("该用户账号已经存在");
        }
        user.setPassword(null);
        userService.updateById(user);
        return RetDTO.success();
    }

    @ApiOperation("修改用户密码")
    @PutMapping("/password")
    public RetDTO<?> updatePassword(@ApiParam("{ password, newPassword, id }")
                                        @RequestBody Map<String, Object> map) {
        String oldPass = (String) map.get("password"), newPass = (String) map.get("newPassword");
        // 验证原密码
        Integer id = (Integer) map.get("id");
        User user = userService.getById(id);
        // 加密 form 中的原密码比对
        String encrypt = DigestUtils.md5DigestAsHex(oldPass.getBytes(StandardCharsets.UTF_8));
        if (!Objects.equals(encrypt, user.getPassword())) return RetDTO.error("原密码不正确");
        // 更新密码
        User newUser = new User();
        newUser.setId(id);
        newUser.setPassword(DigestUtils.md5DigestAsHex(newPass.getBytes(StandardCharsets.UTF_8)));
        userService.updateById(newUser);
        return RetDTO.success();
    }
}
